package rpg;
import javax.microedition.media.*;
import java.io.*;
class SoundEffects
{
    private static SoundEffects instance;
    public final String[] mediaType=new String[]{"audio/x-wav","audio/midi","audio/mpeg"};
    private SoundEffects()
    {
               
    }
    static SoundEffects getInstance()
    {
        if (instance == null)
        {
            instance = new SoundEffects();
        }
        return instance;
    }

   
	public Player createPlayer(String filename,int loop)
	{
		Player player;
		try
		{
			InputStream is=getClass().getResourceAsStream(filename);
			String t=filename.substring(filename.indexOf('.')+1,filename.length());
			if(t.equals("mid"))
			player=Manager.createPlayer(is,mediaType[1]);
			else
			if(t.equals("wav"))
			player=Manager.createPlayer(is,mediaType[0]);
			else
			if(t.equals("mp3"))
			player=Manager.createPlayer(is,mediaType[2]);
			else
			return null;
		}
		catch(Exception e)
		{
			return null;
		}
		player.setLoopCount(loop);
		
		return player;
	}

	public void playSound(Player p)
	{
		if(p==null)return;
		try
		{
			if(p.getState()!=Player.STARTED)
			p.start();
		}
		catch(Exception e)
		{
		}
	}

	public void pauseSound(Player p)
	{
		if(p==null)return;
		try
		{
			if(p.getState()==Player.STARTED)
			p.stop();
		}
		catch(Exception e)
		{
		}
	}

	public void stopSound(Player p)
	{
		if(p==null)return;
		try
		{
			if(p.getState()==Player.STARTED)
			p.stop();
			p.deallocate();
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}

	public void closeSound(Player p)
	{
		if(p==null)return;
		try
		{
			stopSound(p);
			p.close();
			p=null;
			System.gc();
		}
		catch(Exception e)
		{
		}
	}
			
}
